import {
	defineStore
} from 'pinia'
import userAPI from '@/api/userAPI'

import {
	jumpTo
} from '@/utils/common';

// 使用options API模式定义
export const useUserStore = defineStore('user', {
	// 定义state
	state: () => ({
		userInfo: {}, // 用户信息 
		avatarCache: {} // 用于缓存已经获取的头像
	}),
	unistorage: true, // 开启后对 state 的数据读写都将持久化
	// 定义action
	actions: {
		//查找头像
		async findAvatar(memberId) {
			const res = this.avatarCache[memberId];
			if (res) {
				let item = {
					avatar: res.avatar,
					realname: res.realname,
					sex: res.sex
				}

				return item;
			} else {
				var row = await this.getAvatar(memberId);
				this.avatarCache[memberId] = row
				return row;
			}
		},

		async getAvatar(userId) {
			// let avatar = ;
			// let realname = ;
			// let sex = ;

			let item = {
				id: userId,
				avatar: "/static/icon/function3.jpg",
				realname: "0",
				sex: "0"
			}

			if (userId > 0) {
				let res = await userAPI.getUserBase(userId);

				item.avatar = res.data.avatar;
				if (item.avatar) {

				} else {
					item.avatar = "/static/icon/function3.jpg";
				}

				item.realname = res.data.realname
				item.sex = res.data.sex
			}
			return item
		},
		async getUserinfo() {
			if(this.userInfo.id){
				
			} else{
				const res = await userAPI.getUserinfo();
				console.log('🚀 ~ API ~ getUserinfo ~ res:', res)
				this.userInfo = res.data

				if (!this.userInfo.avatar) {
					this.userInfo.avatar = "/static/icon/function2.png"
				}
			}
			
			setTimeout(() => {
				if (this.userInfo.is_vip == 0 || this.userInfo.is_set == 0) {
					jumpTo('/pages/login/code')
				}
			}, 800)

		},
		clear() {
			for (const key in this.userInfo) {
				if (this.userInfo.hasOwnProperty(key)) {
					delete this.userInfo[key];
				}
			}

			for (const key in this.avatarCache) {
				if (this.avatarCache.hasOwnProperty(key)) {
					delete this.avatarCache[key];
				}
			}
		},
		logout() { // 退出
			this.clear();
			uni.$emit("user.logout");
			// router.login({ reLaunch: true });
		}

	}
});